var tools = require('../../libs/tools');
var config = require(tools.rootPath + 'config');
var { connection, pool, model } = require(tools.rootPath + 'libs/model');

const functions = require('../functions');
const core_conf = require('../core_conf');

const datacenter = require(tools.rootPath + 'libs/datacenter');
module.exports = class extends datacenter {
    categorys = {};

    check_catid(catid, module_category) {
        if (module_category == '*') return true;
        return module_category.indexOf(catid) > -1;
    }

    getCatTree(arr, id = 0, lev = 0) {
        let tree = [];
        arr.forEach((v, k) => {
            if (v['parentid'] == id) {
                v['lev'] = lev;
                tree.push(v);
                tree = functions.array_merge(tree, this.getCatTree(arr, v['catid'], lev + 1));
            }
        });

        return tree;
    }

    async category_select(moduleid, name, catid = 0, label = '请选择', extra = '', auth = null) {
        let all_cats = await model.select("select * from szh_category where moduleid=? order by listorder asc", [moduleid]);
        let category_arr = this.getCatTree(all_cats);
        let str = `<select name="${name}" ${extra}>`;
        str += `<option value="0">${label}</option>`;
        category_arr.forEach((v, k) => {
            if (auth !== null && !this.check_catid(v['catid'], auth)) {
                return true;
            }
            let sel;
            if (v['catid'] == catid) {
                sel = `selected="selected"`;
            } else {
                sel = '';
            }
            str += `<option value="${v['catid']}" ${sel}>${functions.str_repeat('&nbsp;', v['lev'] * 4)}┖─&nbsp;${v['catname']}</option>`;
        });

        str += "</select>";
        return str;
    }

    _get_arrparentid(catid, arrparentid = '', n = 1) {
        if (n > 10 || !tools.isObject(this.categorys) || typeof (this.categorys[catid]) == 'undefined') return false;
        let parentid = this.categorys[catid]['parentid'];
        arrparentid = arrparentid ? parentid + ',' + arrparentid : parentid;
        if (parentid) {
            arrparentid = this._get_arrparentid(parentid, arrparentid, ++n);
        } else {
            this.categorys[catid]['arrparentid'] = arrparentid;
        }
        parentid = this.categorys[catid]['parentid'];
        return arrparentid;
    }

    _get_arrchildid(catid) {
        let arrchildid = catid;
        if (tools.isObject(this.categorys)) {
            for (let id in this.categorys) {
                let cat = this.categorys[id];
                if (cat['parentid'] && id != catid && cat['parentid'] == catid) {
                    arrchildid += ',' + this._get_arrchildid(id);
                }
            }
        }
        return arrchildid;
    }

    async cache(moduleid) {
        let categorys = await model.select("select * from szh_category where moduleid=? order by listorder asc", [moduleid]);
        categorys.forEach((v, k) => {
            this.categorys[v['catid']] = v;
        });

        for (let catid in this.categorys) {
            let cat = this.categorys[catid];

            let arrparentid = this._get_arrparentid(catid);
            let arrchildid = this._get_arrchildid(catid);
            let child = !isNaN(arrchildid) ? 0 : 1;
            let tmp = {};
            tmp = functions.object_merge(tmp, cat);
            tmp['arrparentid'] = arrparentid;
            tmp['arrchildid'] = arrchildid;
            tmp['child'] = child;
            tmp['cat_pos'] = await this.get_cat_pos(tmp);

            delete tmp['catid'];
            await model.update("update szh_category set arrparentid=?,arrchildid=?,child=?,cat_pos=? where catid=?", [tmp.arrparentid, tmp.arrchildid, tmp.child, tmp.cat_pos, catid]);
        }
        return true;
    }

    async get_category(catid) {
        catid = parseInt(catid);
        return await model.find("select * from szh_category where catid=?", [catid]);
    }

    async get_cat_pos(CAT) {
        let str = ' &raquo; ';
        let target = '';
        if (tools.isEmpty(CAT)) return '';

        if (typeof (CAT['arrparentid']) == 'undefined' || !CAT['arrparentid']) {
            return CAT['catname'];
        }

        let arrparentids = CAT['arrparentid'] + ',' + CAT['catid'];
        let arrparentid = arrparentids.split(',');
        let pos = '';
        target = target ? ' target="_blank"' : '';
        let CATEGORY = [];
        let ddd = await model.select(`select * from szh_category where catid in (${arrparentids})`);
        ddd.forEach((r) => {
            CATEGORY[r['catid']] = r;
        });

        let last = arrparentid.length - 1;
        arrparentid.forEach((catid, index) => {
            if (!catid || typeof (CATEGORY[catid]) == 'undefined') {
                return true;
            }
            if (index == last) {
                pos += CATEGORY[catid]['catname'] + str;
            } else {
                pos += CATEGORY[catid]['catname'] + str;

            }
        });
        //https://www.cnblogs.com/xxjcai/p/10865321.html
        let _len = str.length;
        if (str && pos.substr(-_len, _len) === str) pos = pos.substr(0, pos.length - _len);
        return pos;
    }

    async max_catid() {
        return await model.value("select max(catid) from szh_category");
    }

    async mod_check_ok(moduleid, catid, parentid) {
        let all_cats = await model.select("select * from szh_category where moduleid=? order by listorder asc", [moduleid]);
        let sub_cats = this.getCatTree(all_cats, catid);
        let ids = [];
        sub_cats.forEach((v) => {
            ids.push(v['catid']);
        });
        //判断所选的父分类是否为当前分类或其后代分类
        if (parentid == catid || functions.in_array(parentid, ids)) return false;
        return true;
    }

    async del_check_ok(catid, moduleid) {
        let r = await model.find("select catid from szh_category where parentid=?", [catid]);
        if (!tools.isEmpty(r)) return false;

        let cf = new core_conf();
        let M = cf.mod_single(moduleid);
        let table = M['module_en'];
        let r2 = await model.value(`select count(*) from szh_${table} where catid=?`, [catid]);
        if (r2) return false;
        return true;
    }

};
